<?php

namespace Drupal\discogs;

use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Entity\EntityViewBuilder;
use Drupal\Core\Render\Element;
use Drupal\Core\Entity\EntityTypeInterface;

/**
 * Render controller for discogs releases.
 */
class ReleaseViewBuilder extends EntityViewBuilder {

  /**
   * {@inheritdoc}
   */
  protected function getBuildDefaults(EntityInterface $entity, $view_mode) {
    $build = parent::getBuildDefaults($entity, $view_mode);
    // The message fields are individually rendered into email templates, so
    // the entity has no template itself.
    unset($build['#theme']);
    return $build;
  }

  /**
   * {@inheritdoc}
   */
  public function buildComponents(array &$build, array $entities, array $displays, $view_mode) {
    parent::buildComponents($build, $entities, $displays, $view_mode);
	/*
    foreach ($entities as $id => $entity) {
      // Add the message extra field, if enabled.
      $display = $displays[$entity->bundle()];
      if ($entity->getMessage() && $display->getComponent('message')) {
        $build[$id]['message'] = array(
          '#type' => 'item',
          '#title' => t('Message'),
          '#plain_text' => $entity->getMessage(),
        );
      }
    }*/
  }

  /**
   * {@inheritdoc}
   */
  public function view(EntityInterface $release, $view_mode = 'full', $langcode = NULL) {
    $build = parent::view($release, $view_mode, $langcode);
	
    if ($view_mode == 'marc21') {
		$build=[];
		
		$header=[
			'Marc Data',
		];
		
		$rows=[];
		
		// Form 001
		$rows[]=[
			'001  '.microtime()
		];
		// Form 028
		foreach($release->get('identifiers') as $identifier) {
			switch($identifier['type']) {
				case 'Label Code': break;
				case 'Barcode':
					$identifier['value']=preg_replace('/ /', '', $identifier['value']);
					switch(strlen($identifier['value'])) {
						case 12:
							$rows[]=[
								'024 10 '.sprintf('@a%s', $identifier['value'])
							];
							break;
						case 13:
							$rows[]=[
								'024 40 '.sprintf('@a%s', $identifier['value'])
							];
							break;
						default:
							$rows[]=[
								'028 53 '.sprintf('@a%s@b%s', $identifier['value'], $identifier['type'])
							];
					}
					break;
				default:
					$rows[]=[
						'028 53 '.sprintf('@a%s@b%s', $identifier['value'], $identifier['type'])
					];
			}
		}
		
		// Form 100
		foreach($release->get('artists') as $artist) {
			$rows[]=[
				'100 0_ '.sprintf('%s%s',
					empty($artist['name'])?'':'@a'.$artist['name'],
					empty($artist['role'])?'':'@e'.$artist['role'])
			];
		}
		
		// Form 245
		$artists=[];
		foreach($release->get('artists') as $artist) {
			$artists[]=$artist['name'].' '.$artist['join'].' ';
		}
		$rows[]=[
			'245 00 '.sprintf('%s%s%s',
				'@a'.$release->get('title'),
				'@h[soundrecording]',
				'/@c'.substr(implode($artists), 0, -2-strlen($artist['join']))
			),
		];
		
		//Form 260
		$rows[]=[
			'260 __ '.sprintf('%s%s%s',
				'@a'.$release->get('country').': ',
				'@b'.$release->get('labels')[0]['name'].', ',
				'@c'.$release->get('released_formatted')
			),
		];
		
		// Form 300
		$rows[]=[
			'300 __ '.'@a'.sprintf('%s %s', $release->get('formats')[0]['qty'], 'sound disc :@bdigital, stereo. ;@c4 3/4 in.'),
		];

		// Form 505
		$field_505=[];
		foreach($release->get('tracklist') as $track) {
			$artists=[];
			$extraartists=[];
			if(isset($track['artists'])) foreach($track['artists'] as $artist) {
				$artists[]=sprintf('/@r%s%s', empty($artist['role'])?'':($artist['role'].': '), $artist['name']);
			}
			if(isset($track['extraartists'])) foreach($track['extraartists'] as $extraartist) {
				$extraartists[]=sprintf('/@r%s, %s', $extraartist['name'], strtolower($extraartist['role']));
			}
			$field_505[]=sprintf('%s%s%s%s',
				''.sprintf('%s%s', empty($track['position'])?'':($track['position'].'. '), $track['title']),
				implode($artists),
				implode($extraartists),
				empty($track['duration'])?'':'@g'.sprintf('(%s)', $track['duration'])
			);
			if(!empty($track['sub_tracks']))
			foreach ($track['sub_tracks'] as $sub_track) {
				$field_505[]=sprintf('%s%s%s',
				    empty($sub_track['position'])?'':($sub_track['position'].'. '),
					$sub_track['title'],
					empty($sub_track['duration'])?'':sprintf('@g(%s)', $sub_track['duration'])
				);
			}
		}
		$rows[]=[
			'505 00 @t'.implode(' --@t', $field_505)
		];
		
		// Form 700
		foreach($release->get('extraartists') as $artist) {
			$rows[]=[
				'700 0_ '.sprintf('@a%s@e%s', $artist['name'], $artist['role']),
			];
		}
		
		// Form 884
		$rows[]=[
			'884 __ @aDiscogs metadata to MARC transformation@g'.date('Ymd').'@k'.sprintf('https://www.discogs.com/release/%s',$release->id()),
		];
		
		$build['data']=[
			'#theme' => 'table',
			'#header' => $header,
			'#rows' => $rows,
		];
		
		return $build;
    }
    return $build;
  }

}
